package com.tf8.treasure.controller;

import com.alibaba.fastjson.JSON;
import com.tf8.treasure.annotation.CheckLogin;
import com.tf8.treasure.domain.BaseRequest;
import com.tf8.treasure.domain.GetMobileCodeRequest;
import com.tf8.treasure.domain.GetMobileCodeResponse;
import com.tf8.treasure.domain.LoginRequest;
import com.tf8.treasure.domain.LoginResponse;
import com.tf8.treasure.domain.QueryMinePageResponse;
import com.tf8.treasure.domain.ResponseInfo;
import com.tf8.treasure.entity.DevicePhone;
import com.tf8.treasure.entity.LtUser;
import com.tf8.treasure.enums.ReturnType;
import com.tf8.treasure.enums.UserLevel;
import com.tf8.treasure.exception.RequestException;
import com.tf8.treasure.service.DevicePhoneService;
import com.tf8.treasure.service.LtUserService;
import com.tf8.treasure.service.MultiMediaService;
import com.tf8.treasure.service.SessionService;
import com.tf8.treasure.service.SmsLogService;
import com.tf8.treasure.utils.AESUtil;
import com.tf8.treasure.utils.DataMask;
import com.tf8.treasure.utils.DateUtil;
import com.tf8.treasure.utils.UuidTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController extends BaseController {

    @Autowired
    private SessionService sessionService;

    @Autowired
    private LtUserService ltUserService;

    @Autowired
    private DevicePhoneService devicePhoneService;

    @Autowired
    private SmsLogService smsLogService;


    @RequestMapping(value = "/getMobileCode", method = RequestMethod.POST)
    public ResponseEntity getMobileCode(@RequestBody @Valid GetMobileCodeRequest getMobileCodeRequest) throws Exception {
        log.info("获取验证码接口入参:{}", JSON.toJSONString(getMobileCodeRequest));
        GetMobileCodeResponse getMobileCodeResponse = new GetMobileCodeResponse();
        String mobile = AESUtil.decode(getMobileCodeRequest.getMobile());
        log.info("解密后的手机号:{}", mobile);
        String code = smsLogService.obtainCode(mobile);
        getMobileCodeResponse.setCode(code);
        //return getMobileCodeResponse;
        return ResponseEntity.ok(new ResponseInfo<>(ReturnType.SUCCESS, getMobileCodeResponse));
    }

    @RequestMapping(value = "/mobileLogin", method = RequestMethod.POST)
    public ResponseEntity mobileLogin(@RequestBody @Valid LoginRequest loginRequest) throws Exception {
        log.info("登录接口入参:{}", JSON.toJSONString(loginRequest));
        String mobileId = loginRequest.getMobileId();
        if (StringUtils.isEmpty(mobileId)) {
            throw new RequestException(ReturnType.PARAM_ERROR);
        }
        LoginResponse lr = new LoginResponse();
        String mobile = AESUtil.decode(loginRequest.getMobile());
        //验证短信验证码
        String verify = smsLogService.verify(mobile, loginRequest.getCode());
        if (verify != null) {
            lr.setMsg(verify);
            lr.setResult("1");
            return ResponseEntity.ok(new ResponseInfo<>(ReturnType.SUCCESS, lr));
        }
        String cookie = UuidTools.getUuid();
        LtUser user = new LtUser();
        user.setMobile(mobile);
        //根据 mobile 修改或 添加用户表
        LtUser saveUser = ltUserService.saveOrUpdate(user);
        //根据 mobileId 修改或 添加设备
        DevicePhone devicePhone = initDevicePhone(loginRequest, saveUser.getUserId(), cookie);
        devicePhoneService.saveOrUpdate(devicePhone);
        addUserToSession(cookie, saveUser);
        lr.setUserId(saveUser.getUserId());
        lr.setCookie(cookie);
        lr.setResult("0");
        return ResponseEntity.ok(new ResponseInfo<>(ReturnType.SUCCESS, lr));
    }


    private DevicePhone initDevicePhone(BaseRequest baseRequest, String userId, String cookie) {
        DevicePhone dp = new DevicePhone();
        dp.setAndroidId(baseRequest.getAndroidId());
        dp.setChannelId(baseRequest.getChannelID());
        dp.setClientId(baseRequest.getClientID());
        dp.setCookie(cookie);
        dp.setDeviceId(baseRequest.getDeviceId());
        dp.setIfa(baseRequest.getIfa());
        dp.setMobileId(baseRequest.getMobileId());
        dp.setModel(baseRequest.getModel());
        dp.setOs(baseRequest.getOs());
        dp.setPlatform(baseRequest.getPlatform());
        dp.setVersion(baseRequest.getVersion());
        dp.setUserid(userId);
        dp.setBrand(baseRequest.getBrand());
        return dp;
    }

    @RequestMapping(value = "/queryMinePage", method = RequestMethod.POST)
    @CheckLogin
    public ResponseEntity queryMinePage(@RequestBody @Valid BaseRequest baseRequest) throws Exception {
        LtUser ltUser = getSession().getLtUser();
        QueryMinePageResponse queryMinePageResponse = new QueryMinePageResponse();
        queryMinePageResponse.setBalance(String.valueOf(ltUser.getBalance()));
        queryMinePageResponse.setPortrait(ltUser.getPortraitUrl());
        queryMinePageResponse.setPhoneNo(DataMask.mask(3, 4, ltUser.getMobile()));
        UserLevel userLevel = UserLevel.getByCode(ltUser.getGrade());
        if (userLevel == UserLevel.Level_2) {//如果是vip会员判断会员是否到期
            Date gradeExpTime = ltUser.getGradeExpTime();
            if (gradeExpTime.before(new Date())) {//已经过期
                queryMinePageResponse.setVipTime("0");
                queryMinePageResponse.setLevel("3");
            } else {
                queryMinePageResponse.setLevel(userLevel.getCode());
                queryMinePageResponse.setVipTime(String.valueOf(DateUtil.getIntervalDays(new Date(), gradeExpTime)));
            }
        } else {
            queryMinePageResponse.setLevel(userLevel.getCode());
            queryMinePageResponse.setVipTime("0");
        }
        queryMinePageResponse.setLevelName(userLevel.getName());
        return ResponseEntity.ok(new ResponseInfo<>(ReturnType.SUCCESS, queryMinePageResponse));
    }

}
